package com.ckmike.order_service.service.impl;

import com.ckmike.order_service.domain.ProductOrder;
import com.ckmike.order_service.service.OrderService;
import com.ckmike.order_service.service.ProductClient;
import com.ckmike.order_service.utils.JsonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * OrderServiceImpl 简要描述
 * <p> TODO:描述该类职责 </p>
 *
 * @author ckmike
 * @version 1.0
 * @date 18-11-7 下午11:55
 * @copyright ckmike
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    @Override
    public ProductOrder saveForRibbon(int userId, int productId) {
        // 获取商品信息
        Map<String, Object> obj = restTemplate.getForObject("http://product-service/api/v1/product/find?id=" + productId, Map.class);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());

        productOrder.setPrice(Double.parseDouble(obj.get("price").toString()));

        productOrder.setProductName(obj.get("name").toString());
        return productOrder;
    }

    @Override
    public ProductOrder saveForFeign(int userId, int productId) {
        String response = this.productClient.findById(productId);
        JsonNode obj = JsonUtil.str2JsonNode(response);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());

        productOrder.setPrice(Double.parseDouble(obj.get("price").toString()));

        productOrder.setProductName(obj.get("name").toString());
        return productOrder;
    }


}
